﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.UI;
using Marbles.Core.Content.Pages;
using Marbles.Core.Content.Sites;
using System.Web;
using System.Web.Compilation;
using System.Web.Hosting;
using System.Web.SessionState;
using System.Security.Permissions;

namespace Marbles.Core.Handlers
{
    public class DynamicPageHandlerFactory : IHttpHandlerFactoryBase
    {
        public string Verbs
        {
            get { return "*"; }
        }

        public bool Validate
        {
            get { return false; }
        }

        public string Path
        {
            get { return "*.aspx"; }
        }

        public string Name
        {
            get { return this.GetType().Name; }
        }

        public System.Web.IHttpHandler GetHandler(System.Web.HttpContext context, string requestType, string url, string pathTranslated)
        {
            if (File.Exists(context.Request.PhysicalPath))
            {
                return PageParser.GetCompiledPageInstance(url, context.Request.PhysicalPath, context);
            }
            
            string pageName = System.IO.Path.GetFileNameWithoutExtension(context.Request.PhysicalPath);
            string path = context.Server.MapPath("~/Render/Content.aspx");
            PageDefinition definition = new PageDefinition(SiteDefinition.GetCurrent().SiteId, pageName);
            context.Items.Add("Name", pageName);
            DirectoryInfo di = new DirectoryInfo(context.Request.MapPath(context.Request.ApplicationPath));
            return GetPageHandler(definition, url, path, context);
        }

        [SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
        private IHttpHandler GetPageHandler(PageDefinition definition, string url, string path, System.Web.HttpContext context)
        {
            return PageParser.GetCompiledPageInstance("~/Render/Content.aspx", path, context);            
        }

        public void ReleaseHandler(System.Web.IHttpHandler handler)
        {

        }
    }
}
